package com.pzb.web.controller.picture;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.pzb.common.config.PzbConfig;
import com.pzb.common.core.domain.entity.PicFile;
import com.pzb.common.utils.file.FileUploadUtils;
import com.pzb.common.utils.file.FileUtil;
import com.pzb.common.utils.file.FileUtils;
import com.pzb.wechat.service.IWechatAppletService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.pzb.common.annotation.Log;
import com.pzb.common.core.controller.BaseController;
import com.pzb.common.core.domain.AjaxResult;
import com.pzb.common.enums.BusinessType;
import com.pzb.picture.service.IPicFileService;
import com.pzb.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;

/**
 * 图片管理Controller
 * 
 * @author pzb
 * @date 2021-09-10
 */
@RestController
@RequestMapping("/picture/file")
public class PicFileController extends BaseController
{
    @Autowired
    private IPicFileService PicFileService;
    @Autowired
    private IWechatAppletService wechatAppletService;

    /**
     * 查询图片管理列表
     */
    @PreAuthorize("@ss.hasPermi('picture:file:list')")
    @GetMapping("/list")
    public TableDataInfo list(PicFile PicFile)
    {
        PicFile.setExtAppid(wechatAppletService.getExtAppid());
        startPage();
        List<PicFile> list = PicFileService.selectPicFileList(PicFile);
        TableDataInfo dataInfo = getDataTable(list);
        List<PicFile> ancestorList=new ArrayList<>();
        if(PicFile.getParentId().longValue() == 0 ){
            PicFile t =new PicFile();
            t.setId(0L);
            t.setFileName("全部文件");
            ancestorList.add(t);
        }else {
            PicFile folder = PicFileService.selectPicFileById(PicFile.getParentId());
            String[] array=folder.getAncestors().split(",");
            for (String s : array) {
                PicFile t;
                if("0".equals(s)){
                    t = new PicFile();
                    t.setId(0L);
                    t.setFileName("全部文件");
                }else {
                    t = PicFileService.selectPicFileById(Long.parseLong(s));
                }
                ancestorList.add(t);
            }
            ancestorList.add(folder);
        }
        dataInfo.setData(ancestorList);
        return dataInfo;
    }

    /**
     * 查询图片视频 不含文件夹
     */
    @PreAuthorize("@ss.hasPermi('picture:file:list')")
    @GetMapping("/fileList")
    public TableDataInfo FileList(PicFile PicFile)
    {
        PicFile.setExtAppid(wechatAppletService.getExtAppid());
        //查询子目录
        PicFile q= new PicFile();
        q.setParentId(PicFile.getParentId());
        q.setType(0);
        List<PicFile> cList= PicFileService.selectPicFileList(q);
        List<Long> parentIds = new ArrayList<>();
        parentIds.add(PicFile.getParentId());
        for (PicFile picture : cList) {
            parentIds.add(picture.getId());
        }
        PicFile.setParentIds(parentIds);
        if(PicFile.getUsable()){
            PicFile.setWidth(800);
            PicFile.setHeight(800);
        }
        startPage();
        List<PicFile> list = PicFileService.selectPictureList(PicFile);
        return getDataTable(list);
    }

    /**
     * 获取目录下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(PicFile picture)
    {
        picture.setExtAppid(wechatAppletService.getExtAppid());
        picture.setType(0);
        List<PicFile> folders = PicFileService.selectPicFileList(picture);
        PicFile p=new PicFile();
        p.setId(0L);
        p.setFileName("全部文件");
        folders.add(p);
        return AjaxResult.success(PicFileService.buildFolderTreeSelect(folders));
    }
    /**
     * 获取图片管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('picture:file:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(PicFileService.selectPicFileById(id));
    }

    /**
     * 新增图片管理
     */
    @PreAuthorize("@ss.hasPermi('picture:file:add')")
    @Log(title = "图片管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PicFile PicFile)
    {
        String extAppid = wechatAppletService.getExtAppid();
        if("1".equals(extAppid)){
            return AjaxResult.error("您还没有小程序!");
        }
        PicFile.setExtAppid(extAppid);
        return toAjax(PicFileService.insertPicFile(PicFile));
    }

    /**
     * 修改图片管理
     */
    @PreAuthorize("@ss.hasPermi('picture:file:edit')")
    @Log(title = "图片管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PicFile PicFile)
    {
        return toAjax(PicFileService.updatePicFile(PicFile));
    }

    /**
     * 移动文件
     */
    @PreAuthorize("@ss.hasPermi('picture:file:edit')")
    @Log(title = "图片管理", businessType = BusinessType.UPDATE)
    @PostMapping("/move")
    public AjaxResult move(@RequestBody PicFile PicFile)
    {
        return toAjax(PicFileService.movePicFiles(PicFile));
    }

    /**
     * 删除文件
     */
    @PreAuthorize("@ss.hasPermi('picture:file:remove')")
    @Log(title = "图片管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(PicFileService.deletePicFileByIds(ids));
    }

    /**
     * 文件上传
     */
    @Log(title = "图片管理", businessType = BusinessType.INSERT)
    @PostMapping("/uploadFiles")
    public AjaxResult uploadFiles(@RequestParam("files") MultipartFile[] files,@RequestParam("parentId") Long parentId) throws IOException
    {
        int count =0;
        String ancestors = "0";
        //祖籍
        if(parentId.longValue()!=0){
            PicFile PicFile = PicFileService.selectPicFileById(parentId);
            ancestors = PicFile.getAncestors()+","+PicFile.getId();
        }
        String extAppid = wechatAppletService.getExtAppid();
        if("1".equals(extAppid)){
            return AjaxResult.error("您还没有小程序!");
        }
        for (MultipartFile file:files){
            PicFile picture=new PicFile();
            picture.setAncestors(ancestors);
            picture.setExtAppid(extAppid);
            picture.setParentId(parentId);
            picture.setSize(file.getSize()/1024);
            String fileName= file.getOriginalFilename();
            picture.setFileName(fileName.substring(0,fileName.lastIndexOf(".")));
            String prefix=fileName.substring(fileName.lastIndexOf("."));
            picture.setSuffix(prefix);
            //获取图片尺寸
            if(!".mp4".equalsIgnoreCase(prefix)){
                picture.setType(1);
                BufferedImage bufferedImage= ImageIO.read(file.getInputStream());
                if(bufferedImage!=null){
                    picture.setWidth(bufferedImage.getWidth());
                    picture.setHeight(bufferedImage.getHeight());
                }
                //压缩图片预览图
                //图片压缩
               // FileUtils.reduceImg(, , 200, 200, null);
            }else {
                picture.setType(2);
            }
            //开始上传文件
            String baseDir = PzbConfig.getStoreFilePath()+"/"+extAppid+"/";
            String filePath = FileUploadUtils.uploadFile(baseDir,file);
            if(!".mp4".equalsIgnoreCase(prefix)){
                //如果是图片对图片进行压缩
                String filename= filePath.substring(filePath.lastIndexOf(".")-36,filePath.lastIndexOf("."));
                logger.info("源文件====>"+baseDir+filename+prefix);
                logger.info("目标文件====>"+baseDir+filename+"_s"+prefix);
                FileUtil.resizePng(baseDir+filename+prefix, baseDir+filename+"_s"+prefix, 200, 200, true);
                String previewPath=filePath.substring(0,filePath.lastIndexOf("."));
                picture.setPreviewPath(previewPath+"_s"+prefix);
            }
            picture.setFilePath(filePath);
            count=count+PicFileService.insertPicFile(picture);
        }
        return toAjax(count);
    }
}
